package dao.impl;

import dao.ICategoryDao;
import jdbc_util.FirstApp;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import pojo.Category;
import java.sql.SQLException;
import java.util.List;

public class CategoryDaoImpl implements ICategoryDao {
    @Override
    public void addCategory(Category category) {
        QueryRunner qr  = null;

        try {
            String sql="insert into category(categoryname) values(?)";
            qr=new QueryRunner();
            qr.update(FirstApp.getConn(),sql,category.getCategoryName());

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    @Override
    public void updateCategory(Category category) {
        QueryRunner qr  = null;
        try {
            String sql="update category set categoryname=? where categoryid =?";
            qr=new QueryRunner();
            qr.update(FirstApp.getConn(),sql,category.getCategoryName(),category.getCategoryid());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    @Override
    public void deleteCategory(int id) {
        QueryRunner queryRunner=new QueryRunner();
        String sql="delete from category where categoryid=?";
        try {
            queryRunner.update(FirstApp.getConn(),sql,id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Category> findAll() {
        List<Category> categoryList=null;
        QueryRunner qr  = null;
        try {
            String sql="Select * from category";
            qr=new QueryRunner();
            categoryList=qr.query(FirstApp.getConn(),sql,new BeanListHandler<Category>(Category.class));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return categoryList;
    }

    @Override
    public Category findById(int id) {
        Category category=null;
        QueryRunner queryRunner=new QueryRunner();
        String sql="select * from category where categoryid=?";
        try {
            Object[] query=queryRunner.query(FirstApp.getConn(),sql,new ArrayHandler(),id);
            if(query.length>0)
            {
                category=new Category();
                category.setCategoryid((Integer) query[0]);
                category.setCategoryName((String) query[1]);
                return category;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
